const express = require('express');
const router = express.Router();
const User = require('../models/user');
const jwt = require('jsonwebtoken');

// 注册
router.post('/register', async (req, res) => {
  try {
    const { username, password, phone } = req.body;

    // 验证必填字段
    if (!username || !password || !phone) {
      return res.status(400).json({
        success: false,
        message: '用户名、密码和手机号不能为空'
      });
    }

    // 检查用户名是否已存在
    const existingUser = await User.findByUsername(username);
    if (existingUser) {
      return res.status(400).json({
        success: false,
        message: '用户名已存在'
      });
    }

    // 创建新用户
    await User.create({ username, password, phone });

    res.json({
      success: true,
      message: '注册成功'
    });
  } catch (error) {
    console.error('注册失败:', error);
    res.status(500).json({
      success: false,
      message: '注册失败'
    });
  }
});

// 登录
router.post('/login', async (req, res) => {
  try {
    const { username, phone, password } = req.body;

    // 验证必填字段
    if (!password || (!username && !phone)) {
      return res.status(400).json({
        success: false,
        message: '请输入用户名或手机号，以及密码'
      });
    }

    // 查找用户
    let user = null;
    if (username) {
      user = await User.findByUsername(username);
    } else if (phone) {
      user = await User.findByPhone(phone);
    }

    if (!user) {
      return res.status(401).json({
        success: false,
        message: '用户名/手机号或密码错误'
      });
    }

    // 验证密码
    const isValid = await User.verifyPassword(password, user.password);
    if (!isValid) {
      return res.status(401).json({
        success: false,
        message: '用户名/手机号或密码错误'
      });
    }

    // 生成 JWT token
    const token = jwt.sign(
      { id: user.id, username: user.username },
      process.env.JWT_SECRET || 'your-secret-key',
      { expiresIn: '24h' }
    );

    res.json({
      success: true,
      message: '登录成功',
      data: {
        token,
        user: {
          id: user.id,
          username: user.username,
          phone: user.phone
        }
      }
    });
  } catch (error) {
    console.error('登录失败:', error);
    res.status(500).json({
      success: false,
      message: '登录失败'
    });
  }
});

// 获取用户信息
router.get('/info', async (req, res) => {
  try {
    const token = req.headers.authorization?.split(' ')[1];
    if (!token) {
      return res.status(401).json({ message: '未提供认证token' });
    }

    const decoded = jwt.verify(token, process.env.JWT_SECRET || 'your-secret-key');
    const user = await User.findById(decoded.id);
    
    if (!user) {
      return res.status(404).json({ message: '用户不存在' });
    }

    res.json({
      id: user.id,
      username: user.username,
      phone: user.phone
    });
  } catch (error) {
    res.status(401).json({ message: '无效的token' });
  }
});

// 验证token
router.get('/verify', async (req, res) => {
  try {
    const token = req.headers.authorization?.split(' ')[1];
    if (!token) {
      return res.status(401).json({
        success: false,
        message: '未提供认证token'
      });
    }

    const user = await User.verifyToken(token);
    if (!user) {
      return res.status(401).json({
        success: false,
        message: '无效的token'
      });
    }

    res.json({
      success: true,
      message: 'token有效',
      data: user
    });
  } catch (error) {
    console.error('验证token失败:', error);
    res.status(401).json({
      success: false,
      message: '验证token失败'
    });
  }
});

module.exports = router; 